package net.zoneland.knowledge.service.impl.search;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import net.zoneland.knowledge.model.EsQuestion;
import net.zoneland.knowledge.model.WordToken;
import net.zoneland.knowledge.model.WordTokens;
import net.zoneland.knowledge.service.EsService;
import net.zoneland.knowledge.utils.GsonUtils;

/**
 * 分词查询.
 *
 * @author: bcc
 * 2021/5/26
 */
@Service("searchOperationImplQueryQuestion")
public class SearchOperationImplQueryQuestion extends AbstractSearchOperation {

    /**
     * logger.
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(SearchOperationImplQueryQuestion.class);

    private static final String ANALYZE_ENDPOINT = "/_analyze";

    @Value("${search.showWordTokens: true}")
    private boolean showWordTokens;

    @Autowired
    private EsService esService;

    @Override
    public boolean needRun(final SearchDto searchDto) {
        return !searchDto.isStopSearch() && StringUtils.isNotEmpty(searchDto.getQaQueryDto().getQueryText());
    }

    @Override
    protected void doSearchOrDeal(final SearchDto searchDto) throws Exception {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("start searchOperationImplQueryQuestion {}", searchDto);
        }
        try {
            final List<EsQuestion> result = esService.queryEsByTokenizer(searchDto.getQaQueryDto());

            if (CollectionUtils.isNotEmpty(result)) {
                //是否显示分词
                if (showWordTokens) {
                    Map<String, String> map = new HashMap<>();
                    map.put("tokenizer", "ik_max_word");
                    map.put("text", searchDto.getQaQueryDto().getQueryText());
                    String rs = esService.maintain(GsonUtils.GSON.toJson(map), ANALYZE_ENDPOINT, "POST");
                    final WordTokens wordTokens = GsonUtils.GSON.fromJson(rs, WordTokens.class);
                    List<String> words = new ArrayList<>();
                    if (null != wordTokens.getTokens()) {
                        for (WordToken wordToken : wordTokens.getTokens()) {
                            words.add(wordToken.getToken());
                        }
                    }
                    searchDto.getQaQueryDto().setWordTokens(words);
                }
                searchDto.addEsQuestions(result);
                searchDto.setStopSearch(needStop(searchDto));
            }
        } catch (Exception e) {
            searchDto.setErrorFlag(true);
            LOGGER.error("SearchOperationImplQueryQuestion error", e);
        }
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("end searchOperationImplQueryQuestion {}", searchDto);
        }
    }



}
